import 'dart:async';

/// event bus
class EventBus {
  /// 工厂模式
  factory EventBus() => _getInstance();

  /// 单例
  static EventBus get instance => _getInstance();
  static EventBus? _instance;

  /// 对应的streamController
  final Map<String, StreamController> _streamControllerMap = {};

  EventBus._internal();

  static EventBus _getInstance() => _instance ??= EventBus._internal();

  /// 检查是否有存在相同的eventName
  bool isExistsEventName(String eventName) =>
      _streamControllerMap.containsKey(eventName);

  /// 注册监听事件
  StreamSubscription<T>? monitoring<T>(String eventName,
      [void onStreamListener(T event)?]) {
    if (!isExistsEventName(eventName)) {
      _streamControllerMap[eventName] = StreamController<T>.broadcast();
    }
    if (onStreamListener != null) {
      return (_streamControllerMap[eventName] as StreamController<T>)
          .stream
          .listen(onStreamListener);
    }
    return null;
  }

  /// 发送事件
  void post<T>(String eventName, T event) {
    if (isExistsEventName(eventName)) {
      _streamControllerMap[eventName]!.add(event);
    }
  }

  /// 取消监听
  void unMonitor(String eventName) {
    if (isExistsEventName(eventName)) {
      _streamControllerMap[eventName]!.close();
      _streamControllerMap.remove(eventName);
    }
  }

  /// 取消注册
  void destroy() {
    if (_streamControllerMap.length > 0) {
      _streamControllerMap.forEach((key, element) => element.close());
      _streamControllerMap.clear();
    }
  }
}

class ExistEventException implements Exception {
  final String message;

  ExistEventException(this.message);

  String toString() {
    Object? message = this.message;
    return "ExistEventException: $message";
  }
}
